import { createRouter, createWebHashHistory } from "vue-router";
import routes from "./routes";
import "nprogress/nprogress.css";
import nProgress from "nprogress";
import { toast } from "@/utils/index.js";
import { getCookies } from "@/utils/auth.js";
import { userAdminStore } from "@/stores/admin.js";
import pinia from "@/stores/index.js";
import { ref } from "vue";
import asyncRoutes from "./methodRouter.js";

// 创建路由实例
const router = createRouter({
	history: createWebHashHistory(),
	routes,
});
// 导出路由实例
export default router;

const { adminState, getAdminInfo } = userAdminStore(pinia);
function generateAsyncRoutes(menus) {
	let hasNewsR = false;
	function mapRoute(menus) {
		menus.forEach((arr) => {
			const hasR = asyncRoutes.find((asycnRoute) => {
				return asycnRoute.path === arr.frontpath;
			});
			if (hasR && !router.hasRoute(arr.frontpath)) {
				router.addRoute("admin", hasR);
				hasNewsR = true;
			}
			if (arr.child && arr.child.length > 0) {
				mapRoute(arr.child);
			}
		});
	}
	mapRoute(menus);
	return hasNewsR;
}

let bool = false;
// 前置路由守卫
router.beforeEach(async (to, from, next) => {
	// 获取登录信用码
	const token = getCookies();
	if (to.meta) {
		document.title = to.meta.title + "-千峰后台管理系统";
	}
	// 如果没有登录 并且不是去登录页，就改变地址方向，跳转到登录页
	if (!token && to.path !== "/login") {
		toast("前先登录", "error");
		return next("/login");
	} else if (token && to.path === "/login") {
		toast("请误重复登录", "success");
		router.back();
		return next({
			path: from.path ? from.path : "/",
		});
	}
	let hasNewsR = false;
	if (token && !bool) {
		await getAdminInfo();
		hasNewsR = generateAsyncRoutes(adminState.adminInfo.menus);
		bool = true;
	}
	nProgress.start();
	hasNewsR ? next({ path: to.path }) : next();
});

// 后置路由守卫
router.afterEach((to, from) => {
	nProgress.done();
});
